﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using HealthManagement.Common;
using Telerik.Windows.Controls;
using PersonalHealth.Data.IService;
using PersonalHealth.Data.Service;
using PersonalHealth.Data.Model;
using Telerik.Windows.Controls.Charting;
using HealthManagement.Models;
using System.Collections;
using UI.Comm.Controls;
using UI.Comm.Common;

namespace HealthManagement.Views
{
    /// <summary>
    /// MeterPanel.xaml 的交互逻辑
    /// </summary>
    public partial class MeterPanel : Page
    {
        IList<MeasureUser> list = new List<MeasureUser>();
        public MeterPanel()
        {
            InitializeComponent();

            if (AppData.User.UserType == UserType.Admin)
                del.Visibility = Visibility.Visible;
            if (AppData.User.UserType == UserType.Doctor)
                del.Visibility = Visibility.Hidden;

            this.radGridView.SelectionChanged += new EventHandler<SelectionChangeEventArgs>(radGridView_SelectionChanged);
            init();
            if (UserGrid.Items.Count > 0)
                UserGrid.SelectedIndex = 0;
            btnPressure.IsSelected = true;

        }

        void radGridView_SelectionChanged(object sender, SelectionChangeEventArgs e)
        {
            if (e.AddedItems == null || e.AddedItems.Count == 0)
                return;
            if (btnECG.IsSelected)
            {
                var obj = e.AddedItems[0] as Measure_ECG;
                PMWindow window = new EcgForm(obj);
                window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                window.ShowDialog();
            }
            if (btnMsg.IsSelected)
            {
                var obj = e.AddedItems[0] as MsgTask;
                PMWindow window = new MessageForm(obj);
                window.Title = "查看消息";
                window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                window.ShowDialog();
            }
            if (btnReport.IsSelected)
            {
                var obj = e.AddedItems[0] as PersonalHealth.Data.Model.HealthReport;
                var window = new HealthReport(obj.Text);
                window.Title = "健康报告";
                window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                window.ShowDialog();

            }
        }

       
        void init()
        {
            int records;
            int pages;
            IMeasureUserService userSer = new MeasureUserService();
            var orderby = new Func<MeasureUser, string>[] { new Func<MeasureUser, string>(c => c.UserName) };
            list = userSer.GetMeasureUserDetailList(c => 1 == 1, orderby,
                        new bool[] { false }, 1, 20, out pages, out records);
            if (list == null)
                return;

            UserGrid.ItemsSource = list.Select(c => new UserModel { Id = c.Id, UserName = c.UserName, ServiceNo = c.ServiceNo }).ToList();
            
        }

        private MeasureUser selectedUser = null;
        private void UserGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (UserGrid.SelectedItem == null)
                return;
            MeasureUser user = list.Single(c => c.Id == (UserGrid.SelectedItem as UserModel).Id);
            UserInfo.DataContext = selectedUser = user;

            rDataPager3.PageIndex = 0;
            queryData();

        }

        private void rDataPager1_PageIndexChanged(object sender, Telerik.Windows.Controls.PageIndexChangedEventArgs e)
        {

        }

        private void searchTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            string key = (sender as RadWatermarkTextBox).Text.Trim().ToLower();
            IList<MeasureUser> subList;
            if (key.Length > 0)
            {
                subList = list.Where(c => c.UserName.ToLower().Contains(key)).ToList();

            }
            else
            {
                subList = list.Where(c => 1 == 1).ToList();
            }
            if (subList == null)
                return;
           UserGrid.ItemsSource = subList.Select(c => new UserModel { Id = c.Id, UserName = c.UserName, ServiceNo = c.ServiceNo });
            if (UserGrid.Items.Count > 0)
                UserGrid.SelectedIndex = 0;
        }

        private void rDataPager3_PageIndexChanged(object sender, Telerik.Windows.Controls.PageIndexChangedEventArgs e)
        {

            if (e.OldPageIndex == -1)
                return;
            DateTimeOffset start = timeStart.SelectedValue.Value;
            DateTimeOffset end = timeEnd.SelectedValue.Value;
            int pageSize = rDataPager3.PageSize;
            int pageIndex = e.NewPageIndex;
            int totalPages;
            int totalRecords;
            if (btnPressure.IsSelected)
            {
                Measure_BPService preSer = new Measure_BPService();

                var preList = preSer.Find(c => c.UserId == selectedUser.Id
                    && c.MeasureTime >= start && c.MeasureTime <= end,
                    new Func<Measure_BP, DateTimeOffset>[]
                        {
                            new Func<Measure_BP,DateTimeOffset>(c=>c.MeasureTime) 
                        },
                    new bool[] { true }, pageIndex + 1, pageSize, out totalPages, out totalRecords)
                    .ToList();
                var preListTotal = new List<Measure_BP>(preList);
                for (int i = 0; i < pageIndex * pageSize; i++)
                {
                    preListTotal.Insert(i, null);
                }
                for (int i = (pageIndex + 1) * pageSize; i < totalRecords; i++)
                {
                    preListTotal.Insert(i, null);
                }
                radGridView.ItemsSource = preListTotal;

                preList = preList.OrderBy(c => c.MeasureTime).ToList();
                List<List<ChartValue>> data = new List<List<ChartValue>>();
                data.Add(preList.Select(c => new ChartValue { Value = c.SBP, Tooltip = c.MeasureTime.ToString("yy年MM月dd日  hh：mm") }).ToList());
                data.Add(preList.Select(c => new ChartValue { Value = c.DBP, Tooltip = c.MeasureTime.ToString("yy年MM月dd日  hh：mm") }).ToList());
                data.Add(preList.Select(c => new ChartValue { Value = c.HR_Value, Tooltip = c.MeasureTime.ToString("yy年MM月dd日  hh：mm") }).ToList());

                RadChart1.ItemsSource = data;
            }
            else if (btnGlucose.IsSelected)
            {
                Measure_BGService sugarSer = new Measure_BGService();
                var sugarList = sugarSer.Find(c => c.UserId == selectedUser.Id
                    && c.MeasureTime >= start && c.MeasureTime <= end,
                    new Func<Measure_BG, DateTimeOffset>[]
                        {
                            new Func<Measure_BG,DateTimeOffset>(c=>c.MeasureTime) 
                        },
                    new bool[] { true }, pageIndex + 1, pageSize, out totalPages, out totalRecords)
                    .ToList();
                var sugarListTotal = new List<Measure_BG>(sugarList);
                for (int i = 0; i < pageIndex * pageSize; i++)
                {
                    sugarListTotal.Insert(i, null);
                }
                for (int i = (pageIndex + 1) * pageSize; i < totalRecords; i++)
                {
                    sugarListTotal.Insert(i, null);
                }
                radGridView.ItemsSource = sugarListTotal;

                sugarList = sugarList.OrderBy(c => c.MeasureTime).ToList();
                List<List<ChartValue>> data = new List<List<ChartValue>>();
                data.Add(sugarList.Select(c => new ChartValue { Value = Convert.ToDecimal(c.BloodGlucose), Tooltip = c.MeasureTime.ToString("yy年MM月dd日  hh：mm") }).ToList());
                RadChart1.ItemsSource = data;
            }
            else if (btnOxygen.IsSelected)
            {
                Measure_BOService oxySer = new Measure_BOService();
                var oxyList = oxySer.Find(c => c.UserId == selectedUser.Id
                    && c.MeasureTime >= start && c.MeasureTime <= end,
                    new Func<Measure_BO, DateTimeOffset>[]
                        {
                            new Func<Measure_BO,DateTimeOffset>(c=>c.MeasureTime) 
                        },
                    new bool[] { true }, pageIndex + 1, pageSize, out totalPages, out totalRecords)
                    .ToList();
                var oxyListTotal = new List<Measure_BO>(oxyList);
                for (int i = 0; i < pageIndex * pageSize; i++)
                {
                    oxyListTotal.Insert(i, null);
                }
                for (int i = (pageIndex + 1) * pageSize; i < totalRecords; i++)
                {
                    oxyListTotal.Insert(i, null);
                }
                radGridView.ItemsSource = oxyListTotal;

                oxyList = oxyList.OrderBy(c => c.MeasureTime).ToList();
                List<List<ChartValue>> data = new List<List<ChartValue>>();
                data.Add(oxyList.Select(c => new ChartValue { Value = Convert.ToDecimal(c.SpO2), Tooltip = c.MeasureTime.ToString("yy年MM月dd日  hh：mm") }).ToList());
                data.Add(oxyList.Select(c => new ChartValue { Value = c.Pulse, Tooltip = c.MeasureTime.ToString("yy年MM月dd日  hh：mm") }).ToList());

                RadChart1.ItemsSource = data;
            }
            else if (btnTemperature.IsSelected)
            {
                Measure_TempService tempSer = new Measure_TempService();
                var tempList = tempSer.Find(c => c.UserId == selectedUser.Id
                    && c.MeasureTime >= start && c.MeasureTime <= end,
                    new Func<Measure_Temp, DateTimeOffset>[]
                        {
                            new Func<Measure_Temp,DateTimeOffset>(c=>c.MeasureTime) 
                        },
                    new bool[] { true }, pageIndex + 1, pageSize, out totalPages, out totalRecords)
                    .ToList();
                var tempListTotal = new List<Measure_Temp>(tempList);
                for (int i = 0; i < pageIndex * pageSize; i++)
                {
                    tempListTotal.Insert(i, null);
                }
                for (int i = (pageIndex + 1) * pageSize; i < totalRecords; i++)
                {
                    tempListTotal.Insert(i, null);
                }
                radGridView.ItemsSource = tempListTotal;

                tempList = tempList.OrderBy(c => c.MeasureTime).ToList();
                List<List<ChartValue>> data = new List<List<ChartValue>>();
                data.Add(tempList.Select(c =>
                new ChartValue { Value = Convert.ToDecimal(c.Temp), Tooltip = c.MeasureTime.ToString("yy年MM月dd日  hh：mm") }).ToList());

                RadChart1.ItemsSource = data;
            }
            else if (btnECG.IsSelected)
            {
                Measure_ECGService ecgSer = new Measure_ECGService();
                var ecgList = ecgSer.Find(c => c.UserId == selectedUser.Id
                    && c.MeasureTime >= start && c.MeasureTime <= end,
                    new Func<Measure_ECG, DateTimeOffset>[]
                        {
                            new Func<Measure_ECG,DateTimeOffset>(c=>c.MeasureTime) 
                        },
                    new bool[] { true }, pageIndex + 1, pageSize, out totalPages, out totalRecords)
                    .ToList();
                var ecgListTotal = new List<Measure_ECG>(ecgList);
                for (int i = 0; i < pageIndex * pageSize; i++)
                {
                    ecgListTotal.Insert(i, null);
                }
                for (int i = (pageIndex + 1) * pageSize; i < totalRecords; i++)
                {
                    ecgListTotal.Insert(i, null);
                }
                radGridView.ItemsSource = ecgListTotal;

                ecgList = ecgList.OrderBy(c => c.MeasureTime).ToList();

                List<List<ChartValue>> lists = new List<List<ChartValue>>();
                DateTime now = DateTime.Now;
                for (int idx = 0; idx < ecgList.Count; idx++)
                {
                    List<ChartValue> ll = new List<ChartValue>();
                    foreach (var i in ecgList[idx].EcgValue)
                    {
                        ll.Add(new ChartValue { Value = i, Time = now.AddMilliseconds(100 * i) });
                    }
                    lists.Add(ll);
                }
                RadChart1.ItemsSource = lists;
            }
            else if (btnMsg.IsSelected)
            {
                IMeasureUserService ser = new MeasureUserService();
                var table = ser.GetMsgTask(start.DateTime, end.DateTime, selectedUser.Id, pageIndex, pageSize, out totalRecords);
                List<MsgTask> listTotal = new List<MsgTask>();
                for (int i = 0; i < pageIndex * pageSize; i++)
                {
                    listTotal.Add(null);
                }
                for (int i = 0; i < table.Rows.Count; i++)
                {
                    MsgTask obj = null;
                    if (table.Rows[i]["category"].ToString() == "消息")
                    {
                        obj = new MsgTask(TextType.Msg);
                        if (int.Parse(table.Rows[i]["typeid"].ToString()) == (int)MessageType.System)
                            obj.TypeName = "系统消息";
                        if (int.Parse(table.Rows[i]["typeid"].ToString()) == (int)MessageType.Doctor)
                            obj.TypeName = "医生消息";
                    }
                    if (table.Rows[i]["category"].ToString() == "任务")
                    {
                        obj = new MsgTask(TextType.Task);
                        if (int.Parse(table.Rows[i]["typeid"].ToString()) == (int)TaskType.Goal)
                            obj.TypeName = "目标任务";
                        if (int.Parse(table.Rows[i]["typeid"].ToString()) == (int)TaskType.Schedule)
                            obj.TypeName = "目标计划";
                    }
                    if (obj != null)
                    {
                        obj.Title = table.Rows[i]["title"].ToString();
                        obj.Content = table.Rows[i]["content"].ToString();
                        obj.SendUser = table.Rows[i]["FromUser"].ToString();
                        obj.SendTime = table.Rows[i]["createDate"].ToString();
                        if (obj.Content.Length < 20)
                        {
                            obj.Description = obj.Content;
                        }
                        else
                        {
                            obj.Description = obj.Content.Substring(0, 20) + "....";
                        }
                        listTotal.Add(obj);
                    }
                }
                for (int i = (pageIndex + 1) * pageSize; i < totalRecords; i++)
                {
                    listTotal.Add(null);
                }
                radGridView.ItemsSource = listTotal;
            }
            else if (btnReport.IsSelected)
            {
                IHealthReportService reportser = new HealthReportService();
                var list = reportser.FindWithUser(c => c.UserId == selectedUser.Id && c.CreateDate >= start && c.CreateDate <= end,
                    new Func<PersonalHealth.Data.Model.HealthReport, DateTimeOffset>[]
                        {
                            new Func<PersonalHealth.Data.Model.HealthReport,DateTimeOffset>(c=>c.CreateDate) 
                        },
                            new bool[] { true }, pageIndex+1, pageSize, out totalPages, out totalRecords);

                List<PersonalHealth.Data.Model.HealthReport> listTotal = new List<PersonalHealth.Data.Model.HealthReport>();
                for (int i = 0; i < pageIndex * pageSize; i++)
                {
                    listTotal.Add(null);
                }
                for (int i = 0; i < list.Count; i++)
                {
                    var obj = new MsgTask(TextType.Report);

                    listTotal.Add(list[i]);
                }
                for (int i = (pageIndex + 1) * pageSize; i < totalRecords; i++)
                {
                    listTotal.Add(null);
                }
                radGridView.ItemsSource = listTotal;
            }
            rDataPager3.PageIndex = pageIndex;


        }

        private void Save_Click(object sender, RoutedEventArgs e)
        {
            rDataPager3.PageIndex = 0;
            queryData();
        }

        private void queryData()
        {
            if (btnECG.IsSelected)
                rDataPager3.PageSize = 5;
            else
                rDataPager3.PageSize = 12;

            if (btnPressure.IsSelected)
                query(MeasureCategory.BloodPressure);
            if (btnGlucose.IsSelected)
                query(MeasureCategory.BloodGlucose);
            if (btnOxygen.IsSelected)
                query(MeasureCategory.OxygenSaturation);
            if (btnTemperature.IsSelected)
                query(MeasureCategory.BodyTemperature);
            if (btnECG.IsSelected)
                query(MeasureCategory.ECG);

            if (btnMsg.IsSelected)
            {
                msgDataBind();
            }

            if (btnReport.IsSelected)
            {
                reportDataBind();
            }


        }

        private void reportDataBind()
        {
            #region gridview
            radGridView.Columns.Clear();
            GridViewDataColumn col;


            col = new GridViewDataColumn();
            TextBlock block = new TextBlock();
            block.Margin = new Thickness(2, 2, 20, 2);
            block.Text = "标题";
            col.Header = block;
            col.Width = GridViewLength.Auto;
            col.DataMemberBinding = new Binding("Title");
            col.IsFilterable = false;
            radGridView.Columns.Add(col);

            col = new GridViewDataColumn();
            block = new TextBlock();
            block.Margin = new Thickness(2, 2, 20, 2);
            block.Text = "发送人";
            col.Header = block;
            col.Width = GridViewLength.Auto;
            col.DataMemberBinding = new Binding("User.UserName");
            col.IsFilterable = false;
            //radGridView.Columns.Add(col);

            col = new GridViewDataColumn();
            block = new TextBlock();
            block.Margin = new Thickness(2, 2, 20, 2);
            block.Text = "到达时间";
            col.Header = block;
            col.Width = GridViewLength.Auto;
            col.DataMemberBinding = new Binding("CreateDate");
            col.IsFilterable = false;
            radGridView.Columns.Add(col);

            DateTimeOffset start = timeStart.SelectedValue.Value;
            DateTimeOffset end = timeEnd.SelectedValue.Value;
            int pageSize = rDataPager3.PageSize;
            int pageIndex = rDataPager3.PageIndex;
            int pages,totalRecords;
            IHealthReportService ser = new HealthReportService();
            var list = ser.FindWithUser(c => c.UserId == selectedUser.Id && c.CreateDate >= start && c.CreateDate <= end,
                new Func<PersonalHealth.Data.Model.HealthReport, DateTimeOffset>[]
                        {
                            new Func<PersonalHealth.Data.Model.HealthReport,DateTimeOffset>(c=>c.CreateDate) 
                        },
                        new bool[] { true }, pageIndex, pageSize, out pages, out totalRecords);

            List<PersonalHealth.Data.Model.HealthReport> listTotal = new List<PersonalHealth.Data.Model.HealthReport>();
            for (int i = 0; i < pageIndex * pageSize; i++)
            {
                listTotal.Add(null);
            }
            for (int i = 0; i < list.Count; i++)
            {
                listTotal.Add(list[i]);
            }
            for (int i = (pageIndex + 1) * pageSize; i < totalRecords; i++)
            {
                listTotal.Add(null);
            }
            radGridView.ItemsSource = listTotal;
            #endregion
        }

        private void msgDataBind()
        {
            #region gridview
            radGridView.Columns.Clear();
            GridViewDataColumn col;

            col = new GridViewDataColumn();
            TextBlock block = new TextBlock();
            block.Margin = new Thickness(2, 2, 20, 2);
            block.Text = "类型";
            col.Header = block;
            col.Width = GridViewLength.Auto;
            col.DataMemberBinding = new Binding("TypeName");
            col.IsFilterable = false;
            radGridView.Columns.Add(col);

            col = new GridViewDataColumn();
            block = new TextBlock();
            block.Margin = new Thickness(2, 2, 20, 2);
            block.Text = "标题";
            col.Header = block;
            col.Width = GridViewLength.Auto;
            col.DataMemberBinding = new Binding("Title");
            col.IsFilterable = false;
            radGridView.Columns.Add(col);


            col = new GridViewDataColumn();
            block = new TextBlock();
            block.Margin = new Thickness(2, 2, 20, 2);
            block.Text = "内容";
            col.Header = block;
            col.Width = GridViewLength.Auto;
            col.DataMemberBinding = new Binding("Description");
            col.IsFilterable = false;
            radGridView.Columns.Add(col);

            col = new GridViewDataColumn();
            block = new TextBlock();
            block.Margin = new Thickness(2, 2, 20, 2);
            block.Text = "发送人";
            col.Header = block;
            col.Width = GridViewLength.Auto;
            col.DataMemberBinding = new Binding("SendUser");
            col.IsFilterable = false;
            radGridView.Columns.Add(col);

            col = new GridViewDataColumn();
            block = new TextBlock();
            block.Margin = new Thickness(2, 2, 20, 2);
            block.Text = "到达时间";
            col.Header = block;
            col.Width = GridViewLength.Auto;
            col.DataMemberBinding = new Binding("SendTime");
            col.IsFilterable = false;
            radGridView.Columns.Add(col);

            DateTimeOffset start = timeStart.SelectedValue.Value;
            DateTimeOffset end = timeEnd.SelectedValue.Value;
            int pageSize = rDataPager3.PageSize;
            int pageIndex = rDataPager3.PageIndex;
            int totalRecords;
            IMeasureUserService ser = new MeasureUserService();
            var table = ser.GetMsgTask(start.DateTime, end.DateTime, selectedUser.Id, pageIndex, pageSize, out totalRecords);
            List<MsgTask> listTotal = new List<MsgTask>();
            for (int i = 0; i < pageIndex * pageSize; i++)
            {
                listTotal.Add(null);
            }
            for (int i = 0; i < table.Rows.Count; i++)
            {
                MsgTask obj = null;
                if (table.Rows[i]["category"].ToString() == "消息")
                {
                    obj = new MsgTask(TextType.Msg);
                    if (int.Parse(table.Rows[i]["typeid"].ToString()) == (int)MessageType.System)
                        obj.TypeName = "系统消息";
                    if (int.Parse(table.Rows[i]["typeid"].ToString()) == (int)MessageType.Doctor)
                        obj.TypeName = "医生消息";
                }
                if (table.Rows[i]["category"].ToString() == "任务")
                {
                    obj = new MsgTask(TextType.Task);
                    if (int.Parse(table.Rows[i]["typeid"].ToString()) == (int)TaskType.Goal)
                        obj.TypeName = "目标任务";
                    if (int.Parse(table.Rows[i]["typeid"].ToString()) == (int)TaskType.Schedule)
                        obj.TypeName = "目标计划";
                }
                if (obj != null)
                {
                    obj.Title = table.Rows[i]["title"].ToString();
                    obj.Content = table.Rows[i]["content"].ToString();
                    obj.SendUser = table.Rows[i]["FromUser"].ToString();
                    obj.SendTime = table.Rows[i]["createDate"].ToString();
                    if (obj.Content.Length < 20)
                    {
                        obj.Description = obj.Content;
                    }
                    else
                    {
                        obj.Description = obj.Content.Substring(0, 20) + "....";
                    }

                    listTotal.Add(obj);
                }
            }
            for (int i = (pageIndex + 1) * pageSize; i < totalRecords; i++)
            {
                listTotal.Add(null);
            }
            radGridView.ItemsSource = listTotal;
            #endregion
        }

        void Tab1_SelectionChanged(object sender, RoutedEventArgs e)
        {
            DateTime now = DateTime.Now;
            if (timeEnd.SelectedValue == null)
                timeEnd.SelectedValue = new DateTime(now.Year, now.Month, now.Day, 23, 59, 59);
            if (timeStart.SelectedValue == null)
                timeStart.SelectedValue = Convert.ToDateTime(now.AddMonths(-1).ToShortDateString());

            if (btnMsg.IsSelected || btnReport.IsSelected || btnECG.IsSelected)
            {
                if (listShowType.IsChecked != true)
                    listShowType.IsChecked = true;
                rbShowType.Visibility = Visibility.Collapsed;
            }
            else
            {
                rbShowType.Visibility = Visibility.Visible;
            }

            rDataPager3.PageIndex = 0;
            //需要先设定 timePicker的初始化值，下面的查询需要用到
            queryData();
        }

        private void RadRadioButton_Checked(object sender, RoutedEventArgs e)
        {
            RadChart1.Visibility = Visibility.Visible;
            radGridView.Visibility = Visibility.Collapsed;
            //rDataPager3.Visibility = Visibility.Collapsed;
        }

        private void RadRadioButton_Checked_1(object sender, RoutedEventArgs e)
        {
            if (IsLoaded)
            {

                RadChart1.Visibility = Visibility.Collapsed;
                radGridView.Visibility = Visibility.Visible;
                //rDataPager3.Visibility = Visibility.Visible;
            }
        }

        private void RefreshClick(object sender, RoutedEventArgs e)
        {
            init();
            if (UserGrid.Items.Count > 0)
                UserGrid.SelectedIndex = 0;

            btnPressure.IsSelected = true;
        }

        private void Add_Click(object sender, RoutedEventArgs e)
        {
            PMWindow window = new UserForm(new Action<int>(
                (id) => { init(); }));
            window.Title = "新增客户";
            window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            window.ShowDialog();
        }

        private void Edit_Click(object sender, RoutedEventArgs e)
        {
            if (selectedUser.UserType == UserType.TestUser)
            {
                Tools.ShowMessage(true, "不能编辑用户体验账号");
                return;
            }

            PMWindow window = new UserForm(selectedUser, new Action<int>(
                (id) => { init(); UserGrid.SelectedValue = id; }));
            window.Title = "编辑客户";
            window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            window.ShowDialog();
        }

        private void del_Click(object sender, RoutedEventArgs e)
        {
            if (selectedUser.UserType == UserType.TestUser)
            {
                Tools.ShowMessage(true, "不能删除用户体验账号");
                return;
            }

            List<UserModel> clickList = Tools.CheckSelectItems<UserModel>(UserGrid);
            UserService ser = new UserService();
            
            if (clickList != null)
            {
                Tools.OpenConfirm("确认要删除选中的数据？", new EventHandler<WindowClosedEventArgs>((object o, WindowClosedEventArgs ex) =>
                {
                    if (ex.DialogResult != null && ex.DialogResult.Value)
                    {
                        foreach (UserModel item in clickList)
                        {
                            ser.Delete(new MeasureUser { Id = item.Id });
                        }
                    }
                }));
            }
            init();
            if (UserGrid.Items.Count > 0)
                UserGrid.SelectedIndex = 0;

            btnPressure.IsSelected = true;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Content = new UserPanel(selectedUser);
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            PMWindow window = new MessageForm(selectedUser);
            window.Title = "填写消息";
            window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            window.ShowDialog();
        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {

            var window = new HealthReport(selectedUser);
            window.Title = "健康报告";
            window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            window.ShowDialog();
        }

        private void btnCard_click(object sender, RoutedEventArgs e)
        {
            var window = new UserCardBind(selectedUser);
            window.Title = "制作卡片";
            window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            window.ShowDialog();
        }

        private void query(MeasureCategory type)
        {
            //MeasureUser selectedUser = UserGrid.SelectedItem as MeasureUser;
            if (selectedUser == null)
                return;
            DateTimeOffset start = timeStart.SelectedValue.Value;
            DateTimeOffset end = timeEnd.SelectedValue.Value;
            int pageSize = rDataPager3.PageSize;
            int pageIndex = rDataPager3.PageIndex;
            int totalPages;
            int totalRecords;
            switch (type)
            {
                case MeasureCategory.BloodPressure:
                    Measure_BPService preSer = new Measure_BPService();

                    var preList = preSer.Find(c => c.UserId == selectedUser.Id
                        && c.MeasureTime >= start && c.MeasureTime <= end,
                        new Func<Measure_BP, DateTimeOffset>[]
                        {
                            new Func<Measure_BP,DateTimeOffset>(c=>c.MeasureTime) 
                        },
                        new bool[] { true }, pageIndex+1, pageSize, out totalPages, out totalRecords)
                        .ToList();
                    var preListTotal = new List<Measure_BP>(preList);
                    for (int i = 0; i < pageIndex * pageSize; i++)
                    {
                        preListTotal.Insert(i, null);
                    }
                    for (int i = (pageIndex + 1) * pageSize; i < totalRecords; i++)
                    {
                        preListTotal.Insert(i, null);
                    }
                    MeasureDataFill.GenerateBloodPressure(radGridView, RadChart1, preList, preListTotal);
                    break;
                case MeasureCategory.BloodGlucose:
                    Measure_BGService sugarSer = new Measure_BGService();
                    var sugarList = sugarSer.Find(c => c.UserId == selectedUser.Id
                        && c.MeasureTime >= start && c.MeasureTime <= end,
                        new Func<Measure_BG, DateTimeOffset>[]
                        {
                            new Func<Measure_BG,DateTimeOffset>(c=>c.MeasureTime) 
                        },
                        new bool[] { true }, pageIndex + 1, pageSize, out totalPages, out totalRecords)
                        .ToList();
                    var sugarListTotal = new List<Measure_BG>(sugarList);
                    for (int i = 0; i < pageIndex * pageSize; i++)
                    {
                        sugarListTotal.Insert(i, null);
                    }
                    for (int i = (pageIndex + 1) * pageSize; i < totalRecords; i++)
                    {
                        sugarListTotal.Insert(i, null);
                    }
                    MeasureDataFill.GenerateBloodGlucose(radGridView, RadChart1, sugarList, sugarListTotal);
                    break;
                case MeasureCategory.OxygenSaturation:
                    Measure_BOService oxySer = new Measure_BOService();
                    var oxyList = oxySer.Find(c => c.UserId == selectedUser.Id
                        && c.MeasureTime >= start && c.MeasureTime <= end,
                        new Func<Measure_BO, DateTimeOffset>[]
                        {
                            new Func<Measure_BO,DateTimeOffset>(c=>c.MeasureTime) 
                        },
                        new bool[] { true }, pageIndex + 1, pageSize, out totalPages, out totalRecords)
                        .ToList();
                    var oxyListTotal = new List<Measure_BO>(oxyList);
                    for (int i = 0; i < pageIndex * pageSize; i++)
                    {
                        oxyListTotal.Insert(i, null);
                    }
                    for (int i = (pageIndex + 1) * pageSize; i < totalRecords; i++)
                    {
                        oxyListTotal.Insert(i, null);
                    }
                    MeasureDataFill.GenerateBloodOxygen(radGridView, RadChart1, oxyList, oxyListTotal);
                    break;
                case MeasureCategory.BodyTemperature:
                    Measure_TempService tempSer = new Measure_TempService();
                    var tempList = tempSer.Find(c => c.UserId == selectedUser.Id
                        && c.MeasureTime >= start && c.MeasureTime <= end,
                        new Func<Measure_Temp, DateTimeOffset>[]
                        {
                            new Func<Measure_Temp,DateTimeOffset>(c=>c.MeasureTime) 
                        },
                        new bool[] { true }, pageIndex + 1, pageSize, out totalPages, out totalRecords)
                        .ToList();
                    var tempListTotal = new List<Measure_Temp>(tempList);
                    for (int i = 0; i < pageIndex * pageSize; i++)
                    {
                        tempListTotal.Insert(i, null);
                    }
                    for (int i = (pageIndex + 1) * pageSize; i < totalRecords; i++)
                    {
                        tempListTotal.Insert(i, null);
                    }
                    MeasureDataFill.GenerateBodyTemperature(radGridView, RadChart1, tempList, tempListTotal);
                    break;
                case MeasureCategory.ECG:
                    Measure_ECGService ecgSer = new Measure_ECGService();
                    var ecgList = ecgSer.Find(c => c.UserId == selectedUser.Id
                        && c.MeasureTime >= start && c.MeasureTime <= end,
                        new Func<Measure_ECG, DateTimeOffset>[]
                        {
                            new Func<Measure_ECG,DateTimeOffset>(c=>c.MeasureTime) 
                        },
                        new bool[] { true }, pageIndex + 1, pageSize, out totalPages, out totalRecords)
                        .ToList();
                    var ecgListTotal = new List<Measure_ECG>(ecgList);
                    for (int i = 0; i < pageIndex * pageSize; i++)
                    {
                        ecgListTotal.Insert(i, null);
                    }
                    for (int i = (pageIndex + 1) * pageSize; i < totalRecords; i++)
                    {
                        ecgListTotal.Insert(i, null);
                    }
                    MeasureDataFill.GenerateECG(radGridView, RadChart1, ecgList, ecgListTotal);
                    break;
                default:
                    break;
            }

            //rDataPager3.PageIndex = 0;

        }

        private void recent3Day_Checked(object sender, RoutedEventArgs e)
        {
            DateTime now = DateTime.Now;
                timeEnd.SelectedValue = new DateTime(now.Year, now.Month, now.Day, 23, 59, 59);
                timeStart.SelectedValue = Convert.ToDateTime(now.AddDays(-2).ToShortDateString());

            rDataPager3.PageIndex = 0;
            queryData();
        }

        private void recentWeek_Checked(object sender, RoutedEventArgs e)
        {
            DateTime now = DateTime.Now;
                timeEnd.SelectedValue = new DateTime(now.Year, now.Month, now.Day, 23, 59, 59);
                timeStart.SelectedValue = Convert.ToDateTime(now.AddDays(-6).ToShortDateString());


            rDataPager3.PageIndex = 0;
            queryData();
        }

        private void recnet1Month_Checked(object sender, RoutedEventArgs e)
        {
            DateTime now = DateTime.Now;
                timeEnd.SelectedValue = new DateTime(now.Year, now.Month, now.Day, 23, 59, 59);
                timeStart.SelectedValue = Convert.ToDateTime(now.AddMonths(-1).ToShortDateString());


            rDataPager3.PageIndex = 0;
            queryData();
        }

        

        

       
    }

    class MeasureDataFill
    {
        public static void GenerateBloodPressure(RadGridView gv, RadChart rc, IList<Measure_BP> list, IList<Measure_BP> listTotal)
        {
            #region gridview
            gv.Columns.Clear();
            GridViewDataColumn col;

            //col = new GridViewDataColumn();
            //col.Header = "测量条件";
            //col.Width = GridViewLength.Auto;
            //col.DataMemberBinding = new Binding("MeasureCondition.name");
            //col.IsFilterable = false;
            //gv.Columns.Add(col);

            col = new GridViewDataColumn();
            TextBlock block = new TextBlock();
            block.Margin = new Thickness(2, 2, 20, 2);
            block.Text = "测量时间";
            col.Header = block;
            col.Width = GridViewLength.Auto;
            col.DataMemberBinding = new Binding("MeasureTime");
            col.IsFilterable = false;
            gv.Columns.Add(col);

            col = new GridViewDataColumn();
            block = new TextBlock();
            block.Margin = new Thickness(2, 2, 20, 2);
            block.Text = "舒张压(mmHg)";
            col.Header = block;
            col.Width = GridViewLength.Auto;
            col.DataMemberBinding = new Binding("DBP");
            col.IsFilterable = false;
            gv.Columns.Add(col);


            col = new GridViewDataColumn();
            block = new TextBlock();
            block.Margin = new Thickness(2, 2, 20, 2);
            block.Text = "收缩压(mmHg)";
            col.Header = block;
            col.Width = GridViewLength.Auto;
            col.DataMemberBinding = new Binding("SBP");
            col.IsFilterable = false;
            gv.Columns.Add(col);


            col = new GridViewDataColumn();
            block = new TextBlock();
            block.Margin = new Thickness(2, 2, 20, 2);
            block.Text = "脉率(bpm)"; ;
            col.Header = block;
            col.Width = GridViewLength.Auto;
            col.DataMemberBinding = new Binding("HR_Value");
            col.IsFilterable = false;
            gv.Columns.Add(col);

            gv.ItemsSource = listTotal;
            #endregion

            list = list.OrderBy(c => c.MeasureTime).ToList();

            #region chart

            rc.SeriesMappings.Clear();
            rc.ItemsSource = null;
            rc.DefaultView.ChartArea.EnableAnimations = true;
            rc.DefaultView.ChartLegend.Header = "血压";

            SeriesMapping mapping = new SeriesMapping();
            mapping.LegendLabel = "收缩压(mmHg)";
            mapping.CollectionIndex = 0;
            SplineSeriesDefinition def = new SplineSeriesDefinition();
            def.ShowItemToolTips = true;
            def.ItemLabelFormat = "0.#";
            def.ShowItemLabels = true;
            def.Appearance = new SeriesAppearanceSettings { };
            mapping.SeriesDefinition = def;
            mapping.ItemMappings.Add(new ItemMapping("Value", DataPointMember.YValue));
            mapping.ItemMappings.Add(new ItemMapping("Tooltip", DataPointMember.Tooltip));
            rc.SeriesMappings.Add(mapping);

            mapping = new SeriesMapping();
            mapping.LegendLabel = "舒张压(mmHg)";
            mapping.CollectionIndex = 1;

            def = new SplineSeriesDefinition();
            def.ShowItemToolTips = true;
            def.ItemLabelFormat = "0.#";
            def.ShowItemLabels = true;
            def.Appearance = new SeriesAppearanceSettings {  };
            mapping.SeriesDefinition = def;
            mapping.ItemMappings.Add(new ItemMapping("Value", DataPointMember.YValue));
            mapping.ItemMappings.Add(new ItemMapping("Tooltip", DataPointMember.Tooltip));
            rc.SeriesMappings.Add(mapping);

            mapping = new SeriesMapping();
            mapping.LegendLabel = "脉率(bpm)";
            mapping.CollectionIndex = 2;
            def = new SplineSeriesDefinition();
            def.ShowItemToolTips = true;
            def.ItemLabelFormat = "0.#";
            def.ShowItemLabels = true;
            def.Appearance = new SeriesAppearanceSettings { };
            mapping.SeriesDefinition = def;
            mapping.ItemMappings.Add(new ItemMapping("Value", DataPointMember.YValue));
            mapping.ItemMappings.Add(new ItemMapping("Tooltip", DataPointMember.Tooltip));
            rc.SeriesMappings.Add(mapping);

            List<List<ChartValue>> data = new List<List<ChartValue>>();
            data.Add(list.Select(c => new ChartValue { Value = c.SBP, Tooltip = c.MeasureTime.ToString("yy年MM月dd日  hh：mm") }).ToList());
            data.Add(list.Select(c => new ChartValue { Value = c.DBP, Tooltip = c.MeasureTime.ToString("yy年MM月dd日  hh：mm") }).ToList());
            data.Add(list.Select(c => new ChartValue { Value = c.HR_Value, Tooltip = c.MeasureTime.ToString("yy年MM月dd日  hh：mm") }).ToList());


            rc.ItemsSource = data;

            #endregion
        }

        public static void GenerateBloodGlucose(RadGridView gv, RadChart rc, IList<Measure_BG> list, IList<Measure_BG> listTotal)
        {
            #region gridview
            gv.Columns.Clear();
            GridViewDataColumn col;

            //col = new GridViewDataColumn();
            //col.Header = "测量条件";
            //col.Width = GridViewLength.Auto;
            //col.DataMemberBinding = new Binding("MeasureCondition.name");
            //col.IsFilterable = false;
            //gv.Columns.Add(col);

            col = new GridViewDataColumn();
            TextBlock block = new TextBlock();
            block.Margin = new Thickness(2, 2, 20, 2);
            block.Text = "测量时间";
            col.Header = block;
            col.Width = GridViewLength.Auto;
            col.DataMemberBinding = new Binding("MeasureTime");
            col.IsFilterable = false;
            gv.Columns.Add(col);

            col = new GridViewDataColumn();
            block = new TextBlock();
            block.Margin = new Thickness(2, 2, 20, 2);
            block.Text = "血糖(mmol/L)";
            col.Header = block;
            col.Width = GridViewLength.Auto;
            col.DataMemberBinding = new Binding("BloodGlucose");
            col.IsFilterable = false;
            gv.Columns.Add(col);

            gv.ItemsSource = listTotal;
            #endregion

            list = list.OrderBy(c => c.MeasureTime).ToList();

            #region chart
            rc.SeriesMappings.Clear();
            rc.ItemsSource = null;
            rc.DefaultView.ChartArea.EnableAnimations = true;
            rc.DefaultView.ChartLegend.Header = "血糖";

            SeriesMapping mapping = new SeriesMapping();
            mapping.LegendLabel = "血糖(mmol/L)";
            mapping.CollectionIndex = 0;
            SplineSeriesDefinition def = new SplineSeriesDefinition();
            def.ShowItemToolTips = true;
            def.ItemLabelFormat = "0.#";
            def.ShowItemLabels = true;
            def.Appearance = new SeriesAppearanceSettings {  };
            mapping.SeriesDefinition = def;
            mapping.ItemMappings.Add(new ItemMapping("Value", DataPointMember.YValue));
            mapping.ItemMappings.Add(new ItemMapping("Tooltip", DataPointMember.Tooltip));
            rc.SeriesMappings.Add(mapping);


            List<List<ChartValue>> data = new List<List<ChartValue>>();
            data.Add(list.Select(c => new ChartValue { Value = Convert.ToDecimal(c.BloodGlucose), Tooltip = c.MeasureTime.ToString("yy年MM月dd日  hh：mm") }).ToList());


            rc.ItemsSource = data;

            #endregion
        }

        public static void GenerateBloodOxygen(RadGridView gv, RadChart rc, IList<Measure_BO> list, IList<Measure_BO> listTotal)
        {
            #region gridview
            gv.Columns.Clear();
            GridViewDataColumn col;

            //col = new GridViewDataColumn();
            //col.Header = "测量条件";
            //col.Width = GridViewLength.Auto;
            //col.DataMemberBinding = new Binding("MeasureCondition.name");
            //col.IsFilterable = false;
            //gv.Columns.Add(col);

            col = new GridViewDataColumn();
            TextBlock block = new TextBlock();
            block.Margin = new Thickness(2, 2, 20, 2);
            block.Text = "测量时间";
            col.Header = block;
            col.Width = GridViewLength.Auto;
            col.DataMemberBinding = new Binding("MeasureTime");
            col.IsFilterable = false;
            gv.Columns.Add(col);

            col = new GridViewDataColumn();
            block = new TextBlock();
            block.Margin = new Thickness(2, 2, 20, 2);
            block.Text = "血氧饱和度(%)";
            col.Header = block;
            col.Width = GridViewLength.Auto;
            col.DataMemberBinding = new Binding("SpO2");
            col.IsFilterable = false;
            gv.Columns.Add(col);


            col = new GridViewDataColumn();
            block = new TextBlock();
            block.Margin = new Thickness(2, 2, 20, 2);
            block.Text = "脉率(bpm)";
            col.Header = block;
            col.Width = GridViewLength.Auto;
            col.DataMemberBinding = new Binding("Pulse");
            col.IsFilterable = false;
            gv.Columns.Add(col);

            gv.ItemsSource = listTotal;
            #endregion

            list = list.OrderBy(c => c.MeasureTime).ToList();

            #region chart

            rc.SeriesMappings.Clear();
            rc.ItemsSource = null;
            rc.DefaultView.ChartArea.EnableAnimations = true;
            rc.DefaultView.ChartLegend.Header = "血氧";

            SeriesMapping mapping = new SeriesMapping();
            mapping.LegendLabel = "血氧饱和度(%)";
            mapping.CollectionIndex = 0;
            SplineSeriesDefinition def = new SplineSeriesDefinition();
            def.ShowItemToolTips = true;
            def.ItemLabelFormat = "0.#";
            def.ShowItemLabels = true;
            def.Appearance = new SeriesAppearanceSettings { };
            mapping.SeriesDefinition = def;
            mapping.ItemMappings.Add(new ItemMapping("Value", DataPointMember.YValue));
            mapping.ItemMappings.Add(new ItemMapping("Tooltip", DataPointMember.Tooltip));
            rc.SeriesMappings.Add(mapping);

            mapping = new SeriesMapping();
            mapping.LegendLabel = "脉率(bpm)";
            mapping.CollectionIndex = 1;
            def = new SplineSeriesDefinition();
            def.ShowItemToolTips = true;
            def.ItemLabelFormat = "0.#";
            def.ShowItemLabels = true;
            def.Appearance = new SeriesAppearanceSettings { };
            mapping.SeriesDefinition = def;
            mapping.ItemMappings.Add(new ItemMapping("Value", DataPointMember.YValue));
            mapping.ItemMappings.Add(new ItemMapping("Tooltip", DataPointMember.Tooltip));
            rc.SeriesMappings.Add(mapping);

            List<List<ChartValue>> data = new List<List<ChartValue>>();
            data.Add(list.Select(c => new ChartValue { Value = Convert.ToDecimal(c.SpO2), Tooltip = c.MeasureTime.ToString("yy年MM月dd日  hh：mm") }).ToList());
            data.Add(list.Select(c => new ChartValue { Value = c.Pulse, Tooltip = c.MeasureTime.ToString("yy年MM月dd日  hh：mm") }).ToList());

            rc.ItemsSource = data;
            #endregion
        }

        public static void GenerateBodyTemperature(RadGridView gv, RadChart rc, IList<Measure_Temp> list, IList<Measure_Temp> listTotal)
        {
            #region gridview
            gv.Columns.Clear();
            GridViewDataColumn col;

            //col = new GridViewDataColumn();
            //col.Header = "测量条件";
            //col.Width = GridViewLength.Auto;
            //col.DataMemberBinding = new Binding("MeasureCondition.name");
            //col.IsFilterable = false;
            //gv.Columns.Add(col);

            col = new GridViewDataColumn();
            TextBlock block = new TextBlock();
            block.Margin = new Thickness(2, 2, 20, 2);
            block.Text = "测量时间";
            col.Header = block;
            col.Width = GridViewLength.Auto;
            col.DataMemberBinding = new Binding("MeasureTime");
            col.IsFilterable = false;
            gv.Columns.Add(col);

            col = new GridViewDataColumn();
            block = new TextBlock();
            block.Margin = new Thickness(2, 2, 20, 2);
            block.Text = "耳温(°C)";
            col.Header = block;
            col.Width = GridViewLength.Auto;
            col.DataMemberBinding = new Binding("Temp");
            col.IsFilterable = false;
            gv.Columns.Add(col);


            gv.ItemsSource = listTotal;
            #endregion

            list = list.OrderBy(c => c.MeasureTime).ToList();

            #region chart
            rc.SeriesMappings.Clear();
            rc.ItemsSource = null;
            rc.DefaultView.ChartArea.EnableAnimations = true;
            rc.DefaultView.ChartLegend.Header = "耳温";

            SeriesMapping mapping = new SeriesMapping();
            mapping.LegendLabel = "耳温(°C)";
            mapping.CollectionIndex = 0;
            SplineSeriesDefinition def = new SplineSeriesDefinition();
            def.ShowItemToolTips = true;
            //def.ItemToolTipFormat = "#VAL{yy年M月d日 hh点mm分}";
            def.ItemLabelFormat = "0.#";
            def.ShowItemLabels = true;
            def.Appearance = new SeriesAppearanceSettings {  };
            mapping.SeriesDefinition = def;
            mapping.ItemMappings.Add(new ItemMapping("Value", DataPointMember.YValue));
            mapping.ItemMappings.Add(new ItemMapping("Tooltip", DataPointMember.Tooltip));
            rc.SeriesMappings.Add(mapping);

            List<List<ChartValue>> data = new List<List<ChartValue>>();
            data.Add(list.Select(c =>
                new ChartValue { Value = Convert.ToDecimal(c.Temp), Tooltip = c.MeasureTime.ToString("yy年MM月dd日  hh：mm") }).ToList());

            rc.ItemsSource = data;

            #endregion
        }

        public static void GenerateECG(RadGridView gv, RadChart rc, IList<Measure_ECG> list, IList<Measure_ECG> listTotal)
        {
            if (list.Count == 0)
            {
                gv.ItemsSource = null;
                return;
            }

            #region gridview
            gv.Columns.Clear();
            GridViewDataColumn col;

            //col = new GridViewDataColumn();
            //col.Header = "测量条件";
            //col.Width = GridViewLength.Auto;
            //col.DataMemberBinding = new Binding("MeasureCondition.name");
            //col.IsFilterable = false;
            //gv.Columns.Add(col);

            col = new GridViewDataColumn() { Width = new GridViewLength(200) };
            TextBlock block = new TextBlock();
            block.Margin = new Thickness(2, 2, 20, 2);
            block.Text = "测量时间";
            col.Header = block;
            col.Width = GridViewLength.Auto;
            col.DataMemberBinding = new Binding("MeasureTime");
            col.IsFilterable = false;
            gv.Columns.Add(col);

            GridViewImageColumn imageCol = new GridViewImageColumn();
            block = new TextBlock();
            block.Margin = new Thickness(2, 2, 20, 2);
            block.Text = "心电图";
            //imageCol.MinWidth = 800;
            imageCol.ImageStretch = Stretch.Fill;
            imageCol.Header = block;
            imageCol.ImageHeight = 80;
            //imageCol.Width = GridViewLength.Auto;
            imageCol.DataMemberBinding = new Binding("EcgDiagram");
            imageCol.IsFilterable = false;
            gv.Columns.Add(imageCol);


            gv.ItemsSource = listTotal;
            #endregion

            list = list.OrderBy(c => c.MeasureTime).ToList();


        }

      


        private static double str2Double(string str)
        {
            if (string.IsNullOrEmpty(str))
                return 0;
            return double.Parse(str);
        }

        private static float str2Float(string str)
        {
            if (string.IsNullOrEmpty(str))
                return 0;
            return float.Parse(str);
        }
    }

    
}
